﻿using System;
using System.Collections.Generic;
using System.Linq;

using Caliburn.Micro;
using Caliburn.Micro.Contrib;
using Caliburn.Micro.Contrib.Results;

using Haushaltsbuch.Domain.Users;
using Haushaltsbuch.Events;
using Haushaltsbuch.Helpers;
using Haushaltsbuch.ViewModels.Interfaces;

namespace Haushaltsbuch.ViewModels.Options
{
    [Export(typeof(IEditUsersViewModel))]
    public class EditUsersViewModel : Conductor<UserDetailViewModel>, IShellContent, IEditUsersViewModel
    {
        private readonly IEventAggregator events;

        private UserInfo selectedUser;
        private UserInfoList users;
        public UserDetailViewModel UserDetailControl { get; set; }

        public UserInfoList Users
        {
            get { return this.users; }
            set
            {
                if (Equals(value, this.users)) return;
                this.users = value;
                this.NotifyOfPropertyChange(() => this.Users);
            }
        }

        public UserInfo SelectedUser
        {
            set
            {
                this.selectedUser = value;
                this.OnSelectedUserChanged();
            }
            get { return this.selectedUser; }
        }

        public bool IsSelected
        {
            get { return this.selectedUser != null; }
        }

        public EditUsersViewModel(IEventAggregator events)
        {
            this.events = events;
            //this.UserControl = new UserViewModel(UserExecutions.Ändern, this.events);
            // this.GetUsers();
        }

        public IEnumerator<IResult> RefreshUsers()
        {
            yield return new DelegateResult(() => this.Users = UserInfoList.Get())
                .OnWorkerThread();
        }

        public void NewUser()
        {
            this.SelectedUser = new UserInfo();
        }

        public void Close()
        {
            this.events.Publish(new ViewChangeEvent("blank"));
        }

        public void GetUsers()
        {
            this.Users = UserInfoList.Get();
        }

        protected override void OnInitialize()
        {
            base.OnInitialize();
            Coroutine.BeginExecute(this.RefreshUsers());
        }

        private void OnSelectedUserChanged()
        {
            this.NotifyOfPropertyChange(() => this.SelectedUser);
            if (this.SelectedUser != null)
                this.EditUser(this.SelectedUser.Id);
        }

        private void EditUser(int id)
        {
            this.ActivateItem(new UserDetailViewModel(id));
        }
    }
}